<?php

namespace App\Http\Middleware;

use \Illuminate\Http\Request;
use Illuminate\Support\Str;
use Closure;

/**
 * 为显示做数据准备
 * @package App\Http\Middleware
 */
class PrepareView
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     *
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $path = $request->path();
        if ($path !== '/') {
            $path = '/' . $path;
        }
        $_SERVER['currentNav'] = $this->getNav($path);
        if (empty($_SERVER['title'])) {
            $_SERVER['title'] = [];
        }
        array_unshift($_SERVER['title'], $this->getTitle($path));
        array_unshift($_SERVER['title'], '腾讯');
        return $next($request);
    }

    public function getNav($path)
    {
        $pathDoc = [
            '/' => 'home',
            '/manageIndex' => 'home',
            '/contact' => 'volunteer',
            '/time_apply' => 'hours',
            '/activity' => 'activity',
            '/manage' => 'activity',
            '/volunteer' => 'volunteer',
            '/hours' => 'hours',
            '/notice' => 'notice',
            '/subscribe_message' => 'notice',
            '/team' => 'team',
            '/team_admin' => 'team',
            '/statistics' => 'statistics',
            '/stat' => 'statistics',
        ];
        foreach ($pathDoc as $p => $name) {
            if ($path == $p || Str::startsWith($path, $p . '/')) {
                return $name;
            }
        }
    }

    public function getTitle($path)
    {
        $pathDoc = [
            '/' => '首页',
            '/contact' => '志愿者列表',
            '/time_apply' => '公益时审核',
            '/activity' => '志愿活动',
            '/manage' => '志愿活动',
            '/volunteer' => '志愿者',
            '/notice' => '通知管理',
            '/subscribe_message' => '小程序通知列表',
            '/team' => '机构管理',
            '/team_admin' => '机构管理',
            '/statistics' => '统计分析',
            '/stat' => '统计分析',
        ];
        foreach ($pathDoc as $p => $name) {
            if ($path == $p || Str::startsWith($path, $p . '/')) {
                return $name;
            }
        }
    }
}
